// 存储用户选择的号码和彩票类型
let currentLotteryType = 'ssq'; // 默认为双色球
let selectedMainBalls = [];
let selectedSpecialBalls = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initializeLotteryTypeSelector();
    initializeBallSelectors();
    attachEventListeners();
});

// 初始化彩票类型选择器
function initializeLotteryTypeSelector() {
    const radioButtons = document.querySelectorAll('input[name="lotteryType"]');
    radioButtons.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.checked) {
                currentLotteryType = this.value;
                updateBallSelectors();
                updateLabels();
                resetSelection();
            }
        });
    });
}

// 更新标签文本
function updateLabels() {
    const mainBallsLabel = document.getElementById('mainBallsLabel');
    const specialBallsLabel = document.getElementById('specialBallsLabel');
    
    if (currentLotteryType === 'ssq') {
        mainBallsLabel.textContent = '红球号码（选择6个）：';
        specialBallsLabel.textContent = '蓝球号码（选择1个）：';
    } else {
        mainBallsLabel.textContent = '前区号码（选择5个）：';
        specialBallsLabel.textContent = '后区号码（选择2个）：';
    }
}

// 初始化球号选择器
function initializeBallSelectors() {
    updateBallSelectors();
    updateLabels();
}

// 根据彩票类型更新球号选择器
function updateBallSelectors() {
    const mainBallContainer = document.getElementById('mainBallContainer');
    const specialBallContainer = document.getElementById('specialBallContainer');
    
    // 清空容器
    mainBallContainer.innerHTML = '';
    specialBallContainer.innerHTML = '';
    
    if (currentLotteryType === 'ssq') {
        // 生成双色球红球号码 (1-33)
        for (let i = 1; i <= 33; i++) {
            const ball = document.createElement('div');
            ball.className = 'ball red-ball unselected';
            ball.textContent = i.toString().padStart(2, '0');
            ball.dataset.number = i;
            ball.addEventListener('click', () => toggleMainBall(i));
            mainBallContainer.appendChild(ball);
        }
        
        // 生成双色球蓝球号码 (1-16)
        for (let i = 1; i <= 16; i++) {
            const ball = document.createElement('div');
            ball.className = 'ball blue-ball unselected';
            ball.textContent = i.toString().padStart(2, '0');
            ball.dataset.number = i;
            ball.addEventListener('click', () => toggleSpecialBall(i));
            specialBallContainer.appendChild(ball);
        }
    } else {
        // 生成大乐透前区号码 (1-35)
        for (let i = 1; i <= 35; i++) {
            const ball = document.createElement('div');
            ball.className = 'ball yellow-ball unselected';
            ball.textContent = i.toString().padStart(2, '0');
            ball.dataset.number = i;
            ball.addEventListener('click', () => toggleMainBall(i));
            mainBallContainer.appendChild(ball);
        }
        
        // 生成大乐透后区号码 (1-12)
        for (let i = 1; i <= 12; i++) {
            const ball = document.createElement('div');
            ball.className = 'ball green-ball unselected';
            ball.textContent = i.toString().padStart(2, '0');
            ball.dataset.number = i;
            ball.addEventListener('click', () => toggleSpecialBall(i));
            specialBallContainer.appendChild(ball);
        }
    }
}

// 重置选择
function resetSelection() {
    selectedMainBalls = [];
    selectedSpecialBalls = [];
    updateSelectedNumbersDisplay();
    
    // 移除所有选中样式
    document.querySelectorAll('.ball.selected').forEach(ball => {
        ball.classList.remove('selected');
        ball.classList.add('unselected');
    });
}

// 切换主球选择状态
function toggleMainBall(number) {
    let maxBalls = currentLotteryType === 'ssq' ? 6 : 5;
    
    const ballElement = document.querySelector(`.main-balls .ball[data-number="${number}"]`);
    
    if (selectedMainBalls.includes(number)) {
        // 取消选择
        selectedMainBalls = selectedMainBalls.filter(n => n !== number);
        ballElement.classList.remove('selected');
        ballElement.classList.add('unselected');
    } else {
        // 选择球号（最多指定数量）
        if (selectedMainBalls.length >= maxBalls) {
            alert(currentLotteryType === 'ssq' ? '红球最多只能选择6个！' : '前区最多只能选择5个！');
            return;
        }
        selectedMainBalls.push(number);
        ballElement.classList.remove('unselected');
        ballElement.classList.add('selected');
    }
    
    updateSelectedNumbersDisplay();
}

// 切换特殊球选择状态
function toggleSpecialBall(number) {
    let maxBalls = currentLotteryType === 'ssq' ? 1 : 2;
    
    const ballElement = document.querySelector(`.special-balls .ball[data-number="${number}"]`);
    
    if (selectedSpecialBalls.includes(number)) {
        // 取消选择
        selectedSpecialBalls = selectedSpecialBalls.filter(n => n !== number);
        ballElement.classList.remove('selected');
        ballElement.classList.add('unselected');
    } else {
        // 选择球号（最多指定数量）
        if (selectedSpecialBalls.length >= maxBalls) {
            alert(currentLotteryType === 'ssq' ? '蓝球最多只能选择1个！' : '后区最多只能选择2个！');
            return;
        }
        selectedSpecialBalls.push(number);
        ballElement.classList.remove('unselected');
        ballElement.classList.add('selected');
    }
    
    updateSelectedNumbersDisplay();
}

// 更新已选号码显示
function updateSelectedNumbersDisplay() {
    const selectedNumbersElement = document.getElementById('selectedNumbers');
    
    if (selectedMainBalls.length === 0 && selectedSpecialBalls.length === 0) {
        selectedNumbersElement.textContent = '请先选择号码';
        return;
    }
    
    let displayText = '';
    const mainLabel = currentLotteryType === 'ssq' ? '红球' : '前区';
    const specialLabel = currentLotteryType === 'ssq' ? '蓝球' : '后区';
    
    if (selectedMainBalls.length > 0) {
        displayText += `${mainLabel}: ` + selectedMainBalls
            .sort((a, b) => a - b)
            .map(n => n.toString().padStart(2, '0'))
            .join(', ');
    }
    
    if (selectedSpecialBalls.length > 0) {
        if (displayText) displayText += '; ';
        displayText += `${specialLabel}: ` + selectedSpecialBalls
            .sort((a, b) => a - b)
            .map(n => n.toString().padStart(2, '0'))
            .join(', ');
    }
    
    selectedNumbersElement.textContent = displayText;
}

// 绑定事件监听器
function attachEventListeners() {
    document.getElementById('queryButton').addEventListener('click', queryLotteryResults);
}

// 查询开奖结果
async function queryLotteryResults() {
    // 验证用户是否已选择完整号码
    let requiredMainBalls = currentLotteryType === 'ssq' ? 6 : 5;
    let requiredSpecialBalls = currentLotteryType === 'ssq' ? 1 : 2;
    
    if (selectedMainBalls.length !== requiredMainBalls || selectedSpecialBalls.length !== requiredSpecialBalls) {
        alert(currentLotteryType === 'ssq' ? 
            '请先选择完整的双色球号码（6个红球+1个蓝球）！' : 
            '请先选择完整的大乐透号码（5个前区+2个后区）！');
        return;
    }
    
    const periodCount = document.getElementById('periodCount').value;
    const resultsElement = document.getElementById('results');
    
    // 显示加载状态
    resultsElement.innerHTML = '<div class="loading">正在查询开奖结果，请稍候...</div>';
    
    try {
        // 通过主进程获取彩票开奖数据
        const response = await window.electronAPI.fetchLotteryData(currentLotteryType, periodCount);
        
        if (!response.success) {
            throw new Error(response.error || '获取数据失败');
        }
        
        // 比对中奖情况
        const winningResults = checkWinningNumbers(response.data);
        
        // 显示结果
        displayResults(winningResults);
    } catch (error) {
        console.error('查询失败:', error);
        resultsElement.innerHTML = `<p style="color: red;">查询失败: ${error.message}</p>`;
    }
}

// 检查中奖情况
function checkWinningNumbers(lotteryData) {
    return lotteryData.map(issue => {
        // 计算主球命中数
        const matchedMainBalls = selectedMainBalls.filter(ball => issue.mainBalls.includes(ball));
        const mainMatches = matchedMainBalls.length;
        
        // 计算特殊球命中数
        const matchedSpecialBalls = selectedSpecialBalls.filter(ball => issue.specialBalls.includes(ball));
        const specialMatches = matchedSpecialBalls.length;
        
        // 根据彩票类型判断中奖等级
        let prizeLevel = 0;
        let prizeDescription = '未中奖';
        
        if (currentLotteryType === 'ssq') {
            // 双色球规则
            if (mainMatches === 6 && specialMatches === 1) {
                prizeLevel = 1;
                prizeDescription = '一等奖';
            } else if (mainMatches === 6 && specialMatches === 0) {
                prizeLevel = 2;
                prizeDescription = '二等奖';
            } else if (mainMatches === 5 && specialMatches === 1) {
                prizeLevel = 3;
                prizeDescription = '三等奖';
            } else if ((mainMatches === 5 && specialMatches === 0) || (mainMatches === 4 && specialMatches === 1)) {
                prizeLevel = 4;
                prizeDescription = '四等奖';
            } else if ((mainMatches === 4 && specialMatches === 0) || (mainMatches === 3 && specialMatches === 1)) {
                prizeLevel = 5;
                prizeDescription = '五等奖';
            } else if (specialMatches === 1) {
                prizeLevel = 6;
                prizeDescription = '六等奖';
            }
        } else {
            // 大乐透规则
            if (mainMatches === 5 && specialMatches === 2) {
                prizeLevel = 1;
                prizeDescription = '一等奖';
            } else if (mainMatches === 5 && specialMatches === 1) {
                prizeLevel = 2;
                prizeDescription = '二等奖';
            } else if (mainMatches === 5 && specialMatches === 0) {
                prizeLevel = 3;
                prizeDescription = '三等奖';
            } else if (mainMatches === 4 && specialMatches === 2) {
                prizeLevel = 4;
                prizeDescription = '四等奖';
            } else if (mainMatches === 4 && specialMatches === 1) {
                prizeLevel = 5;
                prizeDescription = '五等奖';
            } else if ((mainMatches === 3 && specialMatches === 2) || (mainMatches === 4 && specialMatches === 0)) {
                prizeLevel = 6;
                prizeDescription = '六等奖';
            } else if ((mainMatches === 3 && specialMatches === 1) || (mainMatches === 2 && specialMatches === 2)) {
                prizeLevel = 7;
                prizeDescription = '七等奖';
            } else if ((mainMatches === 3 && specialMatches === 0) || (mainMatches === 1 && specialMatches === 2) || (mainMatches === 2 && specialMatches === 1) || (mainMatches === 0 && specialMatches === 2)) {
                prizeLevel = 8;
                prizeDescription = '八等奖';
            }
        }
        
        // 奖金金额（仅为示例）
        const prizeAmounts = {
            ssq: {
                1: '约1000万元',
                2: '约500万元',
                3: '约3000元',
                4: '约200元',
                5: '约10元',
                6: '约5元'
            },
            dlt: {
                1: '约1000万元',
                2: '约50万元',
                3: '约10000元',
                4: '约3000元',
                5: '约300元',
                6: '约200元',
                7: '约100元',
                8: '约5元'
            }
        };
        
        const prizeAmount = prizeLevel > 0 ? prizeAmounts[currentLotteryType][prizeLevel] : '0元';
        
        return {
            ...issue,
            matchedMainBalls,
            matchedSpecialBalls,
            prizeLevel,
            prizeDescription,
            prizeAmount,
            isWinner: prizeLevel > 0
        };
    });
}

// 显示查询结果
function displayResults(results) {
    const resultsElement = document.getElementById('results');
    
    if (results.length === 0) {
        resultsElement.innerHTML = '<p>暂无开奖数据</p>';
        return;
    }
    
    let html = '';
    const mainLabel = currentLotteryType === 'ssq' ? '红球' : '前区';
    const specialLabel = currentLotteryType === 'ssq' ? '蓝球' : '后区';
    const mainBallClass = currentLotteryType === 'ssq' ? 'red-ball' : 'yellow-ball';
    const specialBallClass = currentLotteryType === 'ssq' ? 'blue-ball' : 'green-ball';
    
    results.forEach(result => {
        html += `
            <div class="result-item ${result.isWinner ? 'win' : 'no-win'}">
                <div class="period-info">
                    <span>期号: ${result.period}</span>
                    <span>开奖日期: ${result.date}</span>
                </div>
                <div>您的号码: 
                    <span class="winning-numbers">
                        ${selectedMainBalls.sort((a, b) => a - b).map(num => 
                            `<div class="winning-ball ${mainBallClass}">${num.toString().padStart(2, '0')}</div>`
                        ).join('')}
                        ${selectedSpecialBalls.sort((a, b) => a - b).map(num => 
                            `<div class="winning-ball ${specialBallClass}">${num.toString().padStart(2, '0')}</div>`
                        ).join('')}
                    </span>
                </div>
                <div>开奖号码: 
                    <span class="winning-numbers">
                        ${result.mainBalls.map(num => 
                            `<div class="winning-ball ${mainBallClass}">${num.toString().padStart(2, '0')}</div>`
                        ).join('')}
                        ${result.specialBalls.map(num => 
                            `<div class="winning-ball ${specialBallClass}">${num.toString().padStart(2, '0')}</div>`
                        ).join('')}
                    </span>
                </div>
                ${result.matchedMainBalls.length > 0 ? `
                <div>命中${mainLabel}: 
                    <span class="winning-numbers">
                        ${result.matchedMainBalls.map(num => 
                            `<div class="winning-ball ${mainBallClass}">${num.toString().padStart(2, '0')}</div>`
                        ).join('')}
                    </span>
                </div>` : ''}
                ${result.matchedSpecialBalls.length > 0 ? `
                <div>命中${specialLabel}: 
                    <span class="winning-numbers">
                        ${result.matchedSpecialBalls.map(num => 
                            `<div class="winning-ball ${specialBallClass}">${num.toString().padStart(2, '0')}</div>`
                        ).join('')}
                    </span>
                </div>` : ''}
                <div class="prize-info">中奖等级: ${result.prizeDescription}</div>
                <div class="prize-info">奖金: ${result.prizeAmount}</div>
            </div>
        `;
    });
    
    resultsElement.innerHTML = html;
}